package cc.git.liuyan.customeraiagent.core.embeddingmodel.abstrct;

import cc.git.liuyan.customeraiagent.core.embeddingmodel.EmbeddingModelApiClient;
import cc.git.liuyan.customeraiagent.core.json.Json;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public abstract class AbstractEmbeddingModelApiClient<Api> implements EmbeddingModelApiClient<Api> {
    private final OkHttpClient okHttpClient;
    private final Api giteeAiEmbeddingApi;

    public AbstractEmbeddingModelApiClient(AbstractEmbeddingModelProviderInfo providerInfo, Class<Api> apiClass) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().callTimeout(providerInfo.getApiCallTimeout()).connectTimeout(providerInfo.getApiConnectTimeout()).readTimeout(providerInfo.getApiReadTimeout()).writeTimeout(providerInfo.getApiWriteTimeout());
        if (providerInfo.getApiDispatcher() != null) {
            okHttpClientBuilder.dispatcher(providerInfo.getApiDispatcher());
        }
        if (providerInfo.getApiInterceptors() != null) {
            providerInfo.getApiInterceptors().forEach(interceptor -> okHttpClientBuilder.addInterceptor(interceptor));
        }
        if (providerInfo.getApiProxy() != null) {
            okHttpClientBuilder.proxy(providerInfo.getApiProxy());
        }
        this.okHttpClient = okHttpClientBuilder.build();
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().baseUrl(providerInfo.getBaseUrl()).client(this.okHttpClient);
        retrofitBuilder.addConverterFactory(JacksonConverterFactory.create(Json.OBJECT_MAPPER));
        this.giteeAiEmbeddingApi = retrofitBuilder.build().create(apiClass);
    }

    @Override
    public final Api getApi() {
        return this.giteeAiEmbeddingApi;
    }
}
